/*
 * This page prepares the objects to show on the jsp page of the member's profile
 */
package controllers.classes;

import classes.HibernateUtil;
import dao.CourseDao;
import dao.EmployeeDao;
import dao.StudentDao;
import dao.UserDao;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Course;
import models.Employee;
import models.Student;
import models.User;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Achie
 */
public class EditProfileController extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long memberid = Long.parseLong(request.getParameter("id")); //get member id via url
        HibernateUtil hu = new HibernateUtil();
        //-----------------------------------------------------
        //Get the user object
        //-----------------------------------------------------
        HttpSession hs = request.getSession();
        User usr = (User) hs.getAttribute("user");

        //-----------------------------------------------------
        //Get member details
        //-----------------------------------------------------
        if (hs.getAttribute("userrole").equals("Administrator") || hs.getAttribute("userrole").equals("Teacher")) { //load employee object
            EmployeeDao ed = new EmployeeDao(hu.openSession());
            Employee userdetails = ed.get(memberid);
            request.setAttribute("userdetailsx", userdetails);
            request.setAttribute("role", "employee");
        } else { //load student object
            StudentDao st = new StudentDao(hu.openSession());
            Student userdetails = st.get(memberid);
            //set neccessary attributes 
            request.setAttribute("userdetailsx", userdetails);
            request.setAttribute("role", "student");
        }
        //-----------------------------------------------------

        UserDao ud = new UserDao(hu.openSession());
        User user = ud.get(memberid);

        request.setAttribute("userx", user); //get user object and save it in the request attribute

        //get courses object and save it 
        CourseDao cd = new CourseDao(hu.openSession());
        List<Course> courses = cd.findAll();
        request.setAttribute("courses", courses); //set the courses which the student/employee gives

        hu.close(); //close connection

        RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/edit_member_profile.jsp");
        dispatcher.forward(request, response);

    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HibernateUtil hu = new HibernateUtil();

        long memberid = Long.parseLong(request.getParameter("id"));
        String firstname = request.getParameter("firstname");
        String insertion = request.getParameter("insertion");
        String lastname = request.getParameter("lastname");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        String visibility = request.getParameter("visibility");
        String interests = request.getParameter("interests");

        if (request.getParameter("role").equals("employee")) { //load employee and update
            EmployeeDao ed = new EmployeeDao(hu.openSession());
            Employee emp = ed.get(memberid);

            emp.setFirstname(firstname);
            emp.setGender(gender);
            emp.setInsertion(insertion);
            emp.setLastname(lastname);
            emp.setInterests(interests);
            if (visibility.equals("public")) {
                emp.setHidden(false);
            } else {
                emp.setHidden(true);
            }

            //------------------------------------------------
            //Also update the USER OBJECT (email and other name attributes)
            //------------------------------------------------
            UserDao ud = new UserDao(hu.openSession());
            User usr = ud.get(memberid);
            usr.setFirstname(firstname);
            usr.setInsertion(insertion);
            usr.setLastname(lastname);
            usr.setEmail(email);

            ed.update(emp);
            ud.update(usr);

        } else { //load student and update
            StudentDao sd = new StudentDao(hu.openSession());
            Student student = sd.get(memberid);
            student.setInterests(interests);
            student.setFirstname(firstname);
            student.setGender(gender);
            student.setInsertion(insertion);
            student.setLastname(lastname);
            if (visibility.equals("public")) {
                student.setHidden(false);
            } else {
                student.setHidden(true);
            }

            //------------------------------------------------
            //Also update the USER OBJECT (email and other name attributes)
            //------------------------------------------------
            UserDao ud = new UserDao(hu.openSession());
            User usr = ud.get(memberid);
            usr.setFirstname(firstname);
            usr.setInsertion(insertion);
            usr.setLastname(lastname);
            usr.setEmail(email);

            sd.update(student);
            ud.update(usr);
        }

        String redirect = "userProfile?id=" + memberid;
        response.sendRedirect(redirect);

    }

    public void updateProfilePicture(HttpServletRequest request, HttpServletResponse response) throws ServletException {

        String fileName = null;
        String url;
        String path = "/uploads/profilepictures";
        //-----------------------------------------------------
        //Process the encoded form & save the file on the uploads folder
        //-----------------------------------------------------

        String folderLocation = request.getRealPath(path);
        System.out.println("Volledige url: " + folderLocation);
        HashMap<String, String> formParams = new HashMap<String, String>();
        // String fileName = null;
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        try {
            if (isMultipart) {

                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);

                // Parse the request
                List<FileItem> items = upload.parseRequest(request);

                // Process the uploaded items
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();

                    if (item.isFormField()) {
                        // Process a regular form field
                        formParams.put(item.getFieldName(), item.getString());
                        // fileName = request.getParameter("filename");
                    } else {
                        // Process a file upload
                        fileName = item.getName();
                        File uploadedFile = new File(folderLocation + File.separator + fileName);
                        item.write(uploadedFile);
                    }
                }
            }

            url = path + "/" + fileName;
            long memberid = Long.parseLong(formParams.get("id"));

            HibernateUtil hu = new HibernateUtil();
            EmployeeDao ed = new EmployeeDao(hu.openSession());
            StudentDao sd = new StudentDao(hu.openSession());
            Employee emp = ed.get(memberid);
            if (emp != null) { // its an employee
                emp.setProfileurl(url);
                ed.update(emp);
            } else { //its a student
                Student st = sd.get(memberid);
                st.setProfileurl(url);
                sd.update(st);
            }
            response.sendRedirect("userProfile?id=" + memberid);
        } catch (FileUploadException fue) {
            fue.printStackTrace();
            throw new ServletException(fue.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }


    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
